package com.forum.dao;

import com.forum.bean.Notice;


import com.forum.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/6.
 */
public class NoticeDao {
    private Connection connection = JDBCUtil.getConnection();

    public List listNotice() {
        List<Notice> list = new ArrayList<>();
        PreparedStatement ps;
        ResultSet set = null;
        try {
            String sql = "SELECT * FROM notice ORDER BY notice.date ASC";
            ps = connection.prepareStatement(sql);
            set = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return getList(set, list);
    }

    public int insertNotice(Notice notice, String userId) {
        int row = 0;
        String sql = "INSERT INTO forum.notice (title, content, user_id, date) VALUES (?,?,?,?);";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, notice.getTitle());
            ps.setString(2, notice.getContent());
            ps.setString(3, userId);
            ps.setString(4, notice.getDate());
            row = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    public List listNotice(int notice_id) {
        List<Notice> list = new ArrayList<>();
        ResultSet set = null;
        String sql = "SELECT * FROM notice WHERE notice.id=?";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setInt(1, notice_id);
            set = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return getList(set, list);
    }

    public int deleteNotice(int notice_id) {

        int flag = 0;
        String sql = "DELETE  FROM notice WHERE notice.id=?";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setInt(1, notice_id);
            flag = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }


    private List getList(ResultSet set, List list) {
        try {
            while (set.next()) {
                Notice notice = new Notice();
                notice.setId(set.getInt("id"));
                notice.setTitle(set.getString("title"));
                notice.setContent(set.getString("content"));
                notice.setDate(set.getString("date"));
                list.add(notice);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }


}